#!/bin/bash
####################################################################
# Prey Core On-Demand Functions - (c) 2010 Fork Ltd.
# URL: http://preyproject.com
# License: GPLv3
####################################################################

on_demand_command(){
	openssl s_client -no_ssl2 -quiet -connect $on_demand_host:$on_demand_port 2> /dev/null
	on_demand_cleanup
	# log " -- OpenSSL returned. Removing pipe/lockfile..."
}

on_demand_cleanup(){
	rm -f "$on_demand_pipefile" 2> /dev/null
	kill_process "$on_demand_pipefile" &> /dev/null # the tail process
}

on_demand_stdin(){
	tail -f "$on_demand_pipefile" 2> /dev/null
}

on_demand_loop(){
	on_demand_stdin | on_demand_command | while read data; do
		on_demand_process_msg "$data"
	done
}

on_demand_process_msg(){
	local data="$1"
	[ "$data" == "" ] && return 1
	# log " -- Got message: ${data}."
	local event=`get_json_val "$data" "event"`
	log " -- New event from Prey On-Demand Hub: ${event}"
	case "$event" in
		"ping")
			local last_pinged_at=`get_json_val "$data" 'timestamp'`
			on_demand_ping
			# log " -- Server pinged. Timestamp: ${last_pinged_at}"
			;;
		"info")
			local message=`get_json_val "$data" "message"`
			log " -- Message from server: $message"
			;;
		"message")
			log ' -- Got message!'
			local message_type=`get_json_val "$data" "type"`
			if [ "$message_type" == "text" ]; then
				local message_body=`get_json_val "$data" 'body'`
				if [ "$message_body" == "run_once" ]; then
					"$base_path/prey.sh" --on-demand & disown -h
				else
					log " -- Unknown message: $message_body. Please update to latest version."
				fi
			else
				log " -- Unsupported message type: $message_type. Please update to latest version."
			fi
			;;
		*)
			log " -- Unknown event: ${event}. Please update to latest version."
			;;
	esac
}

enable_on_demand_mode(){

	if [ -f "$on_demand_pipefile" ]; then
		log " -- Prey on-demand is already running!"
		return 1
	fi

	log "\n${bold} >> Setting up on-demand mode!${bold_end}\n"
	echo "" > "$on_demand_pipefile"
	{ on_demand_loop & } 2> /dev/null # suppresses messages
	local on_demand_pid=$!
	log "\n -- On-demand listener running with PID $on_demand_pid!"
	sleep 2

	if [ -f "$on_demand_pipefile" ]; then
		log " -- On-demand mode active!"
		on_demand_handshake
		# echo "$on_demand_pid" > "$on_demand_pidfile"
	else
		log " !! Coundn't set up on-demand."
	fi

}

on_demand_handshake(){
	local protocol_version=1
	log " -- Sending credentials to Prey On Demand Hub...\n"
	on_demand_send "{\"action\": \"connect\", \"data\": {\"client_version\": \"${version}\",\"key\":\"${device_key}\",\"group\":\"${api_key}\", \"protocol\": ${protocol_version} }}"
}

on_demand_ping(){
	local timestamp=$(date +%s)
	on_demand_send "{\"action\": \"ping\", \"data\": {\"timestamp\":${timestamp} }}"
}

on_demand_send(){
	echo "$1" >> "$on_demand_pipefile"
}
